package sl.sl31;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.util.Arrays;

/**
 * 通过注解实现环绕增强
 */
@Aspect
public class AroundLogger {

    private static final Logger logger = Logger.getLogger(AroundLogger.class);

    @Around("execution(* sl.sl2.service.UserService.*(..))")
    public Object aroundLogger(ProceedingJoinPoint jp) throws Throwable {
        logger.info("调用 "+jp.getTarget()+" 的 "+jp.getSignature().getName()+
                " 方法。方法入参："+ Arrays.toString(jp.getArgs()));
        try {
            Object result = jp.proceed();       //执行目标方法并获得其返回值
            logger.info("调用 "+jp.getTarget()+" 的 "+jp.getSignature().getName()+
                    " 方法。方法返回值："+result);
            return result;
        } catch (Throwable e) {
            logger.error(jp.getSignature().getName()+" 方法发生异常："+e);
            throw e;
        }finally {
            logger.info(jp.getSignature().getName()+" 方法结束执行。");
        }
    }

}
